package com.bkitmobile.kesu.appengine.web.server;

import com.bkitmobile.kesu.appengine.storingdata.server.DataStoreManager;
import com.bkitmobile.kesu.appengine.storingdata.server.entity.Place;
import com.bkitmobile.kesu.appengine.storingdata.server.entity.User;

import java.util.*;
import com.bkitmobile.kesu.appengine.web.client.GreetingService;
import com.bkitmobile.kesu.appengine.web.client.entity.ListOfPlace;
import com.bkitmobile.kesu.appengine.web.client.entity.LoginInfo;
import com.bkitmobile.kesu.appengine.web.client.entity.PlaceClient;
import com.bkitmobile.kesu.appengine.web.client.entity.UserInfo;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.bkitmobile.kesu.appengine.mobile.server.Responses;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements
		GreetingService {

	///// input like: usrName(str):pid(str):available(true/false)
	////output: 
	//// success -> thanh cong
	//// relogin -> login lai 1 lan
	//// wronginfo -> sai TK hay MK
	public String doLogin(LoginInfo input) throws IllegalArgumentException {
		DataStoreManager db = new DataStoreManager();
		//String[] split = input.split(":");
		//if (split.length>3) 
		//	throw new IllegalArgumentException("Only 2 argument available");
		//boolean available = split[2].equals("true");
		System.out.print(input.getUserName()+"\n"
				+input.getPid()+"\n");
		int i = db.doLogin(input.getUserName(),input.getPid());
		System.out.print(i);
		if (i==1) 
		{
			this.getThreadLocalRequest().getSession().putValue("usrName", input.getUserName());
			return "success";
		}
		if (i==0) return "relogin";
		if (i==-1) return "wronginfo";
		return "abcxyz";
	}


	@SuppressWarnings("deprecation")
	@Override
	//// input = null
	//// output = userName (or null)
	public String checkLogin(String input) throws IllegalArgumentException {
		// TODO Auto-generated method stub
		Object t = this.getThreadLocalRequest().getSession().getValue("usrName");
		if (t==null)
			return "";
		else
			return (String) t;
	}

	@Override
	public String doLogout(String input) throws IllegalArgumentException {
		// TODO Auto-generated method stub
		Object usrName = this.getThreadLocalRequest().getSession().getValue("usrName");
		if (usrName == null)
			throw new IllegalArgumentException();
		else
		{
			DataStoreManager db = new DataStoreManager();
			db.doLogOut((String) usrName);
			this.getThreadLocalRequest().getSession().removeValue("usrName");
			return "";
		}
	}

	/////// regRes return Username already exist
	///////////////// or success
	public String doRegister(UserInfo input)
			throws IllegalArgumentException {
		// TODO Auto-generated method stub
		System.out.println(input.getUserName() + "\t" + input.getPid() + "\t" + 
				input.getfName() + "\t" + input.getlName() + "\t" + input.getBday()
				+ "\t" + input.getEmail() + "\t sex " +input.isSex() + "\t premium" + input.isPremium() );
		
		final Responses answer = new Responses();
		String res_signal = answer.regResp(input.getUserName(), input.getPid(), 
				input.getfName(),input.getlName(), input.getBday(), 
				input.getEmail(), input.isSex(), !input.isPremium());
		if (res_signal.equals("success"))	
		{
			LoginInfo log_in = new LoginInfo();
			log_in.setUserName(input.getUserName());
			log_in.setPid(input.getPid());
			log_in.setInvisibe(true);
			this.doLogin(log_in);
			return "";	
		}
		else
			throw new IllegalArgumentException();
	}


	@Override
	public ListOfPlace getPlace(String usrName) throws IllegalArgumentException {
		// TODO Auto-generated method stub
		
		Object t = this.getThreadLocalRequest().getSession().getValue("usrName");
		if (t==null)
			throw new IllegalArgumentException();
		else
			usrName = (String) t;
		
		DataStoreManager mgr = new DataStoreManager();
		List<Place> create =  mgr.getPlacesCreated(usrName);
		List<PlaceClient> _return = new ArrayList<PlaceClient> ();
		for (Place i:create)
		{
			PlaceClient insert = new PlaceClient(i.getType(), i.getLongtitude(), i.getLattitude(),
					i.getName(),i.getInfo(),i.getAddress());
			_return.add(insert);
		}
		ListOfPlace addPlaces = new ListOfPlace(_return);
		
		
		return addPlaces;
	}


	public String addPlace(PlaceClient place) throws IllegalArgumentException {
		// TODO Auto-generated method stub
		String usrName;
		Object t = this.getThreadLocalRequest().getSession().getValue("usrName");
		if (t==null)
			throw new IllegalArgumentException();
		else
			usrName = (String) t;
		System.out.println(usrName);
		System.out.println(place.getName());
		System.out.println(place.getType());
		System.out.println(place.getInfo());
		System.out.println(place.getAddress());
		System.out.println( place.getLongtitude());
		System.out.println(place.getLatitude());
		DataStoreManager mgr = new DataStoreManager();
		int i = mgr.createNewPlace(usrName,place.getName(),place.getType(),
				place.getInfo(), place.getAddress(), place.getLongtitude(), 
				place.getLatitude(), this.isPublic(place.getType()),1);
		System.out.println(i);
		if (i==1)
			return "success";
		if (i==-1)
			return "failure";
		return "abc";
	}
	
	private boolean isPublic (String type)
	{
		if (type.equals("Bank") || type.equals("Cinema") || type.equals("Clothes")
			||type.equals("Coffee") || type.equals("Company") || type.equals("Computer")
			||type.equals("Factory")||type.equals("Hotel") || type.equals("Resort") 
			|| type.equals("Restaurant"))
			return false;
		else
			return true;
			
	}


	@Override
	public UserInfo getUsrInfo(String usrName) throws IllegalArgumentException {
		// TODO Auto-generated method stub
		DataStoreManager db = new DataStoreManager();
		User usr = db.getUser(usrName);
		if (usr == null)
		{
			return null;
		}
		UserInfo _ret = new UserInfo();
		_ret.setBday(usr.getBirthDay());
		_ret.setEmail(usr.getEmail());
		_ret.setfName(usr.getFirstName());
		_ret.setlName(usr.getLastName());
		_ret.setPid(usr.getPassword());
		if (usr.getPlaceLeft()>0)
			_ret.setPremium(true);
		else
			_ret.setPremium(false);
		_ret.setSex(usr.getSex());
		_ret.setUserName(usrName);
		_ret.setPlaceLeft(usr.getPlaceLeft());
		return _ret;
	}


	@Override
	public String doUpdate(UserInfo usrName) {
		// TODO Auto-generated method stub
		DataStoreManager db = new DataStoreManager();
		User usr = db.getUser(usrName.getUserName());
		if (usr == null)
		{
			return "";
		}
		usr.setPid(usrName.getPid());
		usr.setFirstName(usrName.getfName());
		usr.setLastName(usrName.getlName());
		usr.setBirthDay(usrName.getBday());
		usr.setEmail(usrName.getEmail());
		usr.setPlaceLeft(usrName.getPlaceLeft());
		db.updateUser(usr);
		
		return "";
	}
}
